package com.qili.service.it.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.entity.CurrentUser;
import com.qili.entity.base.FormType;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorFileTemp;
import com.qili.entity.supervisor.SupervisorProjectForms;
import com.qili.entity.supervisor.SupervisorProjectFormsData;
import com.qili.entity.supervisor.dto.SupervisorProjectFromsDTO;
import com.qili.entity.sys.SysLog;
import com.qili.mapper.search.ItFormMapper;
import com.qili.mapper.supervisor.SupervisorFileMapper;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.util.*;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import tk.mybatis.mapper.entity.Example;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author liuyang
 * @date 2020/11/3
 * @description     书著表单具体业务类
 */
@Log
@Service("ShuZhuFormService")
public class ShuZhuFormServiceImpl extends FormBaseServiceImpl{

    private static final Integer FILE_COUNT = 2;

    @Autowired
    ItFormMapper itFormMapper;

    @Autowired
    SysLogMapper sysLogMapper;

    @Autowired
    private SupervisorFileMapper supervisorFileMapper;

    /**
     * 保存表单数据
     * @param forms
     * @param ifNew
     */
    public void saveFormData(SupervisorProjectFromsDTO forms, boolean ifNew) {
        if(!ifNew){
            //如果form表单不是空(这里代表的是编辑表单页面,而不是新建表单:)
            //把原来的删除:
            SupervisorProjectFormsData formsData = new SupervisorProjectFormsData();
            formsData.setSpfId(forms.getSpfId());
            formsDataService.delete(formsData);
        }
        //书著 副主编
        SupervisorProjectFormsData spfd=new SupervisorProjectFormsData();
        ArrayList<String> strList1 = forms.getStrList1();
        if(CollectionUtil.isNotEmpty(strList1)){
            for(int i=0;i<strList1.size();i++){
                spfd.setSpfdataId(IdUtil.simpleUUID());
                spfd.setSpfId(forms.getSpfId());
                spfd.setData1(strList1.get(i));
                spfd.setTableIndex(i);
                spfd.setData10("zhubian");
                formsDataService.insertSelective(spfd);
            }
        }
        //书著 编委
        ArrayList<String> strList2 = forms.getStrList2();
        if(CollectionUtil.isNotEmpty(strList2)){
            for(int j=0;j<strList2.size();j++){
                spfd.setSpfdataId(IdUtil.simpleUUID());
                spfd.setSpfId(forms.getSpfId());
                spfd.setData1(strList2.get(j));
                spfd.setTableIndex(j);
                spfd.setData10("bianwei");
                formsDataService.insertSelective(spfd);
            }
        }
    }

    /**
     * 保存表单文件
     * @param forms
     * @param ifNew
     */
    public void saveFormFile(SupervisorProjectFromsDTO forms, boolean ifNew) {
        ArrayList<String> fileIds = new ArrayList<String>();
        //书著文件:
        ArrayList<String> shuZhuFileIds = forms.getStrList3();
        //书著扫描件:
        ArrayList<String> shuZhuScanFileIds = forms.getStrList4();
        if(!ifNew){
            //如果form表单不是空(这里代表的是编辑表单页面,而不是新建表单:)
            //编辑表单页面不需要移动文件，只是操作删除数组:
            ArrayList<String> strList9 = forms.getStrList9();
            if(CollectionUtil.isNotEmpty(strList9)){
                for(String delFileId:strList9){
                    //设置为回收站状态:
                    SupervisorFile delFile = new SupervisorFile();
                    delFile.setId(delFileId);
                    delFile.setDeleteState("2");
                    delFile.setDeleteUser(CommonUtil.getUserId());
                    delFile.setDeleteDate(DateUtil.getCurrentDateString());
                    dicService.updateByPrimaryKeySelective(delFile);
                    SupervisorFile supervisorFile = supervisorFileMapper.selectByPrimaryKey(delFileId);
                    if(supervisorFile!=null){
                        insertFileLog(supervisorFile.getFileName());
                    }


                }
            }

        }else{
            //这里是新建表单逻辑:
            //新建表单核心文件夹:
            String formCode = forms.getSpfF30();
            FormType formType = FormType.getFormType(formCode);
            //生成表单核心文件夹路径：（例如:/书著/2021_001_xx书著）
            //该方法执行后,会把核心文件设置为formDto的Obj1对象
            createCenterDic(forms);
            SupervisorFile centFile = (SupervisorFile) forms.getObj1();
            if(CollectionUtil.isNotEmpty(shuZhuFileIds)){
                fileIds.addAll(shuZhuFileIds);
            }
            if(CollectionUtil.isNotEmpty(shuZhuScanFileIds)){
                fileIds.addAll(shuZhuScanFileIds);
            }
            if(CollectionUtil.isNotEmpty(fileIds)){
                //这里面存放的是临时文件id:
                for(String shuzhuFileId : fileIds){
                    SupervisorFileTemp supervisorFileTemp = fileTempService.selectByPrimaryKey(shuzhuFileId);
                    //1.移动操作系统文件 newFile为移动后的文件
                    File newFile = moveTempFile(supervisorFileTemp, forms);
                    //2.复制数据到正式文件表
                    //更改url
                    supervisorFileTemp.setUrl(newFile.getPath());
                    SupervisorFile newSupervisorFile = new SupervisorFile();
                    BeanUtil.copyNotNullBean(supervisorFileTemp,newSupervisorFile);
                    newSupervisorFile.setZskfileType("2");
                    newSupervisorFile.setDeleteState("1");
                    //表单中的每一个文件都指向该核心文件
                    newSupervisorFile.setLinkId(centFile.getId());
                    fileService.insertFile(newSupervisorFile,(SupervisorFile) forms.getObj1());
                    //3.删除临时文件表
                    fileTempService.deleteByPrimaryKey(shuzhuFileId);
                }
            }
        }
    }

    public void insertFileLog(String filename) {
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setType("DEL");
        sysLog.setText("删除文件");
        sysLog.setParam("参数:文件名称：" + filename);
        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
        CurrentUser user = CommonUtil.getUser();
        sysLog.setUserName(user.getUsername());
        sysLogMapper.insert(sysLog);
    }
    /**
     * 获取表单数据
     * @param formTypeCode
     * @param formDto
     * @param model
     */
    public void getFormData(String formTypeCode, SupervisorProjectFromsDTO formDto, Model model) {
        Example zhubianExample = new Example(SupervisorProjectFormsData.class);
        zhubianExample.and().andEqualTo("data10","zhubian")
                .andEqualTo("spfId",formDto.getSpfId());
        zhubianExample.setOrderByClause("table_index asc");
        List<SupervisorProjectFormsData> select1 = formsDataService.selectByExample(zhubianExample);
        if(CollectionUtil.isNotEmpty(select1)){
            select1.stream().sorted(Comparator.comparing(SupervisorProjectFormsData::getTableIndex)).collect(Collectors.toList());
            if(model != null){
                model.addAttribute("zhubian",select1);
            }else{
                formDto.setObj1(select1);
            }
        }
        //获取编委:
        Example bianweiExample = new Example(SupervisorProjectFormsData.class);
        bianweiExample.and().andEqualTo("data10","bianwei")
                .andEqualTo("spfId",formDto.getSpfId());
        bianweiExample.setOrderByClause("table_index asc");
        List<SupervisorProjectFormsData> select3 = formsDataService.selectByExample(bianweiExample);
        if(CollectionUtil.isNotEmpty(select3)){
            select3.stream().sorted(Comparator.comparing(SupervisorProjectFormsData::getTableIndex)).collect(Collectors.toList());
            if(model != null){
                model.addAttribute("bianwei",select3);
            }else{
                formDto.setObj2(select3);
            }
        }
    }

    public Integer getMaxCount(SupervisorProjectFromsDTO formInfo) {
        return itFormMapper.getMaxCount(formInfo);
    }

    public ReType selectFormBook(SupervisorProjectFromsDTO formInfo, String page, String limit) {
        if(StringUtils.isNotBlank(formInfo.getSpfF1())){
            formInfo.setSpfF1("%"+formInfo.getSpfF1()+"%");
        }
        if(StringUtils.isNotBlank(formInfo.getSpfF4())){
            formInfo.setSpfF4("%"+formInfo.getSpfF4()+"%");
        }
        Page<SupervisorProjectFromsDTO> tPage = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        List<SupervisorProjectForms> supervisorProjectForms = itFormMapper.selectSZTZ(formInfo);
        List<SupervisorProjectFromsDTO> formDto = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(supervisorProjectForms)){
            formDto = getFormDto(formInfo.getSpfF30(), supervisorProjectForms);
        }
        return new ReType(tPage.getTotal(),formDto);
    }

    private List<SupervisorProjectFromsDTO> getFormDto(String formTypeCode,List<SupervisorProjectForms> supervisorProjectForms) {
        List<SupervisorProjectFromsDTO> formsDtoList = new ArrayList<SupervisorProjectFromsDTO>();
        for(int i=0;i<supervisorProjectForms.size();i++){
            SupervisorProjectForms aForm = supervisorProjectForms.get(i);
            SupervisorProjectFromsDTO aDto = changeToDto(aForm);
            getFormData(formTypeCode,aDto,null);
            setFormFiles(formTypeCode,aDto);
            aDto.setFileInd(i+1);
            formsDtoList.add(aDto);
        }
        return formsDtoList;
    }

    /**
     * 获取软著统计表格数据:
     *
     //姓名
     var name = $('#name').val();
     //版次时间
     var start = $('#bc_date_start'+defaultTabInd).val();
     var end = $('#bc_date_end'+defaultTabInd).val();
     var jsondata = {
     spfF1:name
     };
     jsondata['obj1'] = start;
     jsondata['obj2'] = end;
     return jsondata;
     * @return
     */
    @Override
    public ReType selectFormStatisticsTableData(String formTypeCode, SupervisorProjectFromsDTO formInfo, String index, String page, String limit) {
        Page<Object> objects = PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
        List<Map<String,Object>> resultMap = new ArrayList<>();
                switch (index){
            case "0":
                resultMap = itFormMapper.getShuZhuStatistics0(formInfo);
                break;
            case "1":
                resultMap = itFormMapper.getShuZhuStatistics1(formInfo);
                break;

        }

        //获取根据符合条件的年份列表:
        return new ReType(objects.getTotal(),resultMap);
    }

    public List<String> getSpfIdList(SupervisorProjectFromsDTO formInfo) {
        return itFormMapper.getSpfIdListForShuzhu(formInfo);
    }
}
